﻿using System;

namespace Core
{
    /// <summary>
    /// 自定义帧循环系统
    /// </summary>
    //[AllowMultiComponent]
    public class FrameSystem : Core.Component, IAwake<int>, IUpdate
    {
        public int FrameRate { get; private set; }
        public int FrameCount { get; private set; }
        public float FrameTime { get; private set; }

        public float TimeScale { get; set; }

        private float elapsedTime;

        public void Awake(int frame_rate)
        {
            FrameRate = frame_rate;
            FrameTime = 1.0f / frame_rate;

            SysTime.SetSystem(this);

            elapsedTime = 0;
            TimeScale = 1;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            elapsedTime = 0;
        }

        public void Update()
        {
            elapsedTime += UnityEngine.Time.deltaTime * TimeScale;

            while (elapsedTime >= FrameTime)
            {
                elapsedTime -= FrameTime;

                FrameCount++;

                try
                {
                    G.Factory.Tick();
                }
                catch (Exception e)
                {
                    log.err(e);
                    break;
                }
            }
        }
    }
}
